package com.blog.controller;

import com.blog.pojo.Users;
import com.blog.service.UsersService;
import com.blog.service.impl.UsersServiceImpl;
import com.blog.utils.MD5Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * 用户模块控制层
 */
@WebServlet(value = "/UsersServlet.do")
public class UsersServlet extends HttpServlet {

    //创建一个业务逻辑层的对象
    UsersService usersService = new UsersServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求乱码
        req.setCharacterEncoding("UTF-8");
        //获取action参数
        String action = req.getParameter("action"); // login

        if ("login".equals(action)) {
            //用户登录
            user_login(req, resp);
        } else {
            //剩余逻辑
        }

    }

    private void user_login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取表单中username的值
        String username = req.getParameter("username");
        //获取表单中password的值
        String password = req.getParameter("password");
        //获取用户输入的验证码
        String code = req.getParameter("code");
        System.out.println("登录的用户名是:" + username);
        System.out.println("登录的密码是:" + password);
        System.out.println("登录用户输入的验证码是:" + code);
        //获取系统生成的验证码
        String systemCode = (String) req.getSession().getAttribute("systemCode");
        //不区分大小写比较验证码
        if (systemCode.equalsIgnoreCase(code)) {
            //把密码转换为密文登录
            String salt = "java";
            password = MD5Utils.string2MD5(password + salt);
            System.out.println("登录的密码密文:" + password);
            //调用业务逻辑层的登录方法
            Users users = usersService.login(username, password);
            if (users != null) {
                System.out.println("登录成功");
                //登录成功，跳转到数据展示
                //存储登录用户的session
                HttpSession session = req.getSession();
                session.setAttribute("user",users);
                //重定向 首页
                resp.sendRedirect("/Blog/IndexServlet.do");
            } else {
                //登录失败
                System.out.println("账号或密码错误");
                //向Request中存值
                req.setAttribute("msg", "账号或密码错误");
                //转发调用登录页面，需要共享request中的数据
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }else{
            //向Request中存值
            req.setAttribute("msg", "验证码错误");
            //转发调用登录页面，需要共享request中的数据
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }
}
